//
//  AppDelegate.m
//  Sneakers
//
//  Created by 胡光健 on 2017/9/19.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "AppDelegate.h"
#import <AlipaySDK/AlipaySDK.h>
#import <Bugly/Bugly.h>
#import "UPPaymentControl.h"

@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate

- (void)setRootWindowToTabBar{
    _tabBarVc = [[HJTabBarViewController alloc] init];
    self.window.rootViewController = _tabBarVc;
    [self.window makeKeyAndVisible];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self setRootWindowToTabBar];
    // 崩溃日志
    [Bugly startWithAppId:@"2f86813a4c"];
    
    
    //注册shareSDK
    [[HJShareManager manager] registerShareSDK];
    [WXApi registerApp:@"wx77ce449425419979"];
    
    // 环信客服
    HOptions *option = [[HOptions alloc] init];
    option.appkey = @"1114171220115619#sneaker";
    option.tenantId = @"52559";
    option.apnsCertName = @"sneaker";
    
    [application registerForRemoteNotifications];
    UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound |   UIUserNotificationTypeAlert;
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
    
    
    HError *initError = [[HChatClient sharedClient] initializeSDKWithOptions:option];
    if (initError) { // 初始化错误
    }
    
    //键盘设置
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    [[IQKeyboardManager sharedManager] setEnable:YES];
    manager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    manager.enableAutoToolbar = NO;
    manager.keyboardDistanceFromTextField = 2;
    
    [[NSUserDefaults standardUserDefaults] setObject:@(0) forKey:@"row"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
   
}
// APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}

// APP将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}



- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
   
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }else if([url.host isEqualToString:@"uppayresult"]) {//银联支付处理支付结果
        [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
            if([code isEqualToString:@"success"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"YINLIANPAYS" object:nil];
            }else if([code isEqualToString:@"fail"]) {
                //交易失败
                [[NSNotificationCenter defaultCenter] postNotificationName:@"YINLIANPAYF" object:nil];
            }else if([code isEqualToString:@"cancel"]) {
                //交易取消
                [[NSNotificationCenter defaultCenter] postNotificationName:@"YINLIANPAYC" object:nil];
            }
        }];
    }else {// 微信
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }else if([url.host isEqualToString:@"uppayresult"]){//银联支付处理支付结果
        [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
            if([code isEqualToString:@"success"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"YINLIANPAYS" object:nil];
            }else if([code isEqualToString:@"fail"]) {
                //交易失败
                [[NSNotificationCenter defaultCenter] postNotificationName:@"YINLIANPAYF" object:nil];
            }else if([code isEqualToString:@"cancel"]) {
                //交易取消
                [[NSNotificationCenter defaultCenter] postNotificationName:@"YINLIANPAYC" object:nil];
            }
        }];
    }else { // 微信
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}

- (void)onReq:(BaseReq *)req {
    
}
-(void)onResp:(BaseResp *)resp {
    NSString *strTitle;
    strTitle = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *respInfo = (PayResp *)resp;
        NSLog(@"returnKey %@", respInfo.returnKey);
        switch (resp.errCode) {
            case WXSuccess: {
                strTitle = @"支付成功";
                [mNotificationCenter  postNotificationName:@"didWeChatPaySuccessNoti" object:nil];
            } break;
            case WXErrCodeCommon: {    // 签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                strTitle = @"支付失败";
            } break;
            case WXErrCodeUserCancel: { // 用户点击取消并返回
                strTitle = @"支付取消";
            } break;
            case WXErrCodeSentFail: {   // 发送失败
                strTitle = @"支付失败";
            } break;
            case WXErrCodeUnsupport: {  // 微信不支持
                strTitle = @"微信不支持";
            } break;
            case WXErrCodeAuthDeny:  {  // 授权失败
                strTitle = @"授权失败";
            } break;
            default: break;
        }
        if (resp.errCode != WXSuccess) {
            [mNotificationCenter postNotificationName:@"didWechatPayError" object:nil];
        }
    }
}
@end
